#include "PropertyAccessor.h"
#include "../utils/TypeConverter.h"
#include <QDebug>
#include <QObject>
#include <QString>
#include <QVariant>
#include <exception>
#include <pybind11/embed.h>
#include <pybind11/stl.h>

// 定义py命名空间别名
namespace py = pybind11;

pybind11::object PropertyAccessor::getProperty(QObject *obj,
                                               const QString &propertyName) {
  if (!obj || propertyName.isEmpty()) {
    return pybind11::object();
  }

  // 获取属性值
  QVariant prop = obj->property(propertyName.toStdString().c_str());

  // 转换为Python对象
  return TypeConverter::qVariantToPyObject(prop);
}

bool PropertyAccessor::setProperty(QObject *obj, const QString &propertyName,
                                   const pybind11::object &value) {
  if (!obj || propertyName.isEmpty()) {
    return false;
  }

  try {
    // 将Python对象转换为QVariant
    QVariant variant = TypeConverter::pyObjectToQVariant(value);

    // 设置属性值
    return obj->setProperty(propertyName.toStdString().c_str(), variant);
  } catch (const std::exception &e) {
    qWarning() << "设置属性失败:" << e.what();
    return false;
  }
}